<template>
  <div>
    <el-form class="search">
      <el-form-item label="职位搜索">
        <el-input placeholder="请输入职位名称" style="width: 400px;" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" :disabled="!keyword">查询</el-button>
        <el-button @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
    <el-card>
      <el-button type="primary" @click="addRole" icon="Plus">添加角色</el-button>
      <!-- 表格组件 -->
      <el-table style="margin: 13px 0;" border :data="allRole">
        <!-- <el-table-column align="center" type="selection"></el-table-column> -->
        <el-table-column align="center" label="#" type="index" :index="formatIndex()"></el-table-column>
        <el-table-column align="center" label="ID" prop="id"></el-table-column>
        <el-table-column align="center" label="职位名称" prop="roleName"></el-table-column>
        <el-table-column align="center" label="创建时间" show-overflow-tooltip prop="createTime"></el-table-column>
        <el-table-column align="center" label="更新时间" show-overflow-tooltip prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <!-- @vue-ignore -->
          <template #="{ row }">
            <!-- row是用户对象的数据 -->
            <el-button icon="User" type="success" size="small" @click="setPermission(row)">分配权限</el-button>
            <el-button icon="Edit" type="primary" size="small" @click="updateRole(row)">编辑</el-button>
            <el-popconfirm :title="`您确认要删除吗？`" width="200" @confirm="deleteRole(row.id)">
              <template #reference>
                <el-button icon="Delete" type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 -->
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 40]" background
        layout="prev, pager, next, jumper,->,sizes,total" :total="total" @current-change="getHasRole"
        @size-change="getHasRole" />
      <!-- 对话框 -->
      <el-dialog :title="roleParams.id ? '修改角色' : '添加角色'" v-model="dialogTableVisible" :close-on-click-modal="false">
        <el-form>
          <el-form-item label="角色名称">
            <el-input placeholder="请输入角色名称" v-model="roleParams.roleName"></el-input>
          </el-form-item>
        </el-form>
        <div class="button">
          <el-button type="primary" @click="save">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </el-dialog>
      <!-- 抽屉组件 -->
      <el-drawer v-model="drawer">
        <template #header>
          <h4>分配菜单与按钮的权限</h4>
        </template>
        <template #default>
          <!-- 树形控件 -->
          <el-tree ref="tree" :data="menuArr" show-checkbox default-expand-all :props="defaultProps" node-key="id"
            :default-checked-keys="selectArr">
          </el-tree>
        </template>
        <template #footer>
          <el-button type="primary" @click="handler">确定</el-button>
          <el-button @click="reset">取消</el-button>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { reqGetRoleList, reqAddOrUpdateRole, reqAllPermission, reqSetPermission, reqDelOneOrGroupRole } from "@/api/user/role/index";
import type { RecordsResponseData, RecordsData, Record, AddOrUpdateRole, MenuResponseData, MenuList } from '@/api/user/role/type'
import { ElMessage } from "element-plus";
const pageNo = ref<number>(1)
const pageSize = ref<number>(5)
const total = ref<number>(0)
const keyword = ref<string>('')
// 收集新增岗位的数据
const roleParams = reactive<AddOrUpdateRole>({
  roleName: '',
})
// 存储全部已有的职位
const allRole = ref<RecordsData>([])
// 页面挂载获取数据
onMounted(() => {
  getHasRole()
})
// 获取已有职位列表
// 页面挂载时默认捞第一页
const getHasRole = async (val = 1) => {
  pageNo.value = val
  const res: RecordsResponseData = await reqGetRoleList(pageNo.value, pageSize.value, keyword.value)
  if (res.code == 200) {
    allRole.value = res.data.records
    total.value = res.data.total
  }
}
// 格式化序号
const formatIndex = () => {
  return (pageNo.value - 1) * pageSize.value + 1
}
// 搜索框回调
const search = async () => {
  try {
    await getHasRole()
    ElMessage.success("搜索成功")
  } catch (error) {
    console.log(error);
  }

}
// 清空搜索框
const clear = () => {
  keyword.value = ''
  getHasRole()
}
// 对话框的显示和隐藏
const dialogTableVisible = ref<boolean>(false)
// 添加角色的回调
const addRole = () => {
  dialogTableVisible.value = true
}
// 更新角色的回调
const updateRole = (row: Record) => {
  dialogTableVisible.value = true
  console.log(row);
  Object.assign(roleParams, row)
}
// 确定按钮的回调
const save = async () => {
  const res = await reqAddOrUpdateRole(roleParams)
  if (res.code === 200) {
    ElMessage.success(roleParams.id ? "修改成功" : "添加成功")
    // 重新获取数据
    getHasRole(roleParams.id ? pageNo.value : 1 as number)
  } else {
    ElMessage.error(roleParams.id ? "修改失败" : "添加失败")
  }
  cancel()
}
// 取消按钮的回调
const cancel = () => {
  dialogTableVisible.value = false
  Object.assign(roleParams, {
    createTime: "",
    id: 0,
    remark: '',
    roleName: '',
    updateTime: ''
  })
}
// 定义一个数组，存放权限的信息
const menuArr = ref<MenuList>([])
// 控制抽屉的显示和隐藏
const drawer = ref<boolean>(false)
// 树形控件需要展示的数据和选择的数据
const defaultProps = {
  children: 'children',
  label: 'name'
}
// 准备一个存放末端select为真的对象的id数组
const selectArr = ref<number[]>([])
// 分配权限按钮的回调
const setPermission = async (row: Record) => {
  drawer.value = true
  // 合并对象，到时候接口需要使用
  Object.assign(roleParams, row)
  // 根据信息id获取权限数据
  const res: MenuResponseData = await reqAllPermission(row.id as number)
  if (res.code == 200) {
    menuArr.value = res.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}
// 过滤数组的方法
const filterSelectArr = (allData: MenuList, initArr: number[]) => {
  allData.forEach((item: any) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}
// el-tree的组件实例
const tree = ref<any>()
// 修改权限确定按钮的回调
const handler = async () => {
  // 职位id
  const roleId = roleParams.id as number
  // 选中节点的ID
  const arr = tree.value.getCheckedKeys()
  // 半选节点的ID
  const halfArr = tree.value.getHalfCheckedKeys()
  // 合并Id
  const permissionId = arr.concat(halfArr)
  // 发请求下发权限
  const res = await reqSetPermission(roleId, permissionId)
  if (res.code == 200) {
    ElMessage.success("分配权限成功")
    getHasRole()
  } else {
    ElMessage.error("分配权限失败")
  }
  reset()
}
// 取消分配权限的回调
const reset = () => {
  // 关闭弹框
  drawer.value = false
  selectArr.value = []
  menuArr.value = []
  // 清空数据
  Object.assign(roleParams, {
    createTime: "",
    id: 0,
    remark: '',
    roleName: '',
    updateTime: ''
  })
}
// 删除角色的回调
const deleteRole = async (id: number) => {
  const res = await reqDelOneOrGroupRole([id])
  console.log(res);
  if (res.code == 200) {
    ElMessage.success("删除成功")
    getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage.error("删除失败")
  }
}
</script>

<style scoped lang="scss"> .search {
   display: flex;

   .el-form-item {
     margin-right: 40px;
   }
 }

 .el-dialog {
   .button {
     margin-left: 70%;
   }
 }
</style>
